package org.wzq.controller;

/**
 * project: forum
 * ate: 14-9-20
 * author: wzq
 * description: TODO
 */

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.wzq.biz.Section;
import org.wzq.dao.SectionDao;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/manager")
public class ManagerController {
    @Autowired
    private SectionDao sectionDao;

    protected final Log logger = LogFactory.getLog(getClass());

    public void printReq(HttpServletRequest req) {
        logger.info(req.getMethod() + "  " + req.getRequestURI());
    }

    @RequestMapping(value = "home", method = RequestMethod.GET)
    public ModelAndView managerHomePage(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        return new ModelAndView("manager/home");
    }

    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ModelAndView managerUser(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        return new ModelAndView("manager/users");
    }

    @RequestMapping(value = "sections", method = RequestMethod.GET)
    public ModelAndView managerSections(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        List<Section> sectionList = sectionDao.getSectionAll();
        return new ModelAndView("manager/sections", "sectionList", sectionList);
    }

    @RequestMapping(value = "section", method = RequestMethod.POST)
    @ResponseBody
    public String addSection(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        String sectionName = req.getParameter("sectionName");
        Section section = new Section(sectionName);
        sectionDao.saveOrUpdate(section);
        return "add success";
    }

    @RequestMapping(value = "section/{sectionId}", method = RequestMethod.DELETE)
    @ResponseBody
    public String deleteSection(@PathVariable String sectionId, HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        sectionDao.deleteSection(sectionId);
        return "delete success";
    }
}
